﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using Developer.Entity;
using Super.Framework.Common.Secure;
using Super.Framework.Log;

namespace Developer.Service
{
    public class SecurityService
    {
        private const string _salt = "rz8LuOtFBXphj9WQfvFh";
        // private static int _expirationMinutes = 10;

        /// <summary>
        ///生成token 方便API调用  
        /// </summary>
        public static string GenerateToken(string username, string password, string ip, string userAgent, long ticks)
        {
            string hash = string.Join(":", username, password, ip, userAgent, ticks.ToString());

            return hash.Encrypt(_salt);

        }

        public static Adminers TokenValid(string token, string ip, string userAgent)
        {
            Adminers result = null;
            //测试
            var key = token.Decrypt(_salt);
            string[] parts = key.Split(':');
            string account = parts[0];
            string password = parts[1];
            var user = SysInfo.DB.Adminers.FirstOrDefault(a => a.Account == account );
            result = user;
            //测试

            //try
            //{

            //    var key = token.Decrypt(_salt);
            //    string[] parts = key.Split(':');
            //    if (parts.Length == 5)
            //    {

            //        string account = parts[0];             //account
            //        string password = parts[1];          //password
            //        long ticks = long.Parse(parts[4]);  //ticks
            //        DateTime timeStamp = new DateTime(ticks);

            //        if (timeStamp>DateTime.Now)
            //        {
            //            var user =  SysInfo.DB.Users.FirstOrDefault(a => a.Account == account && a.IsAbort == false);
            //            if (user != null)
            //            {
            //                //string computedToken = GenerateToken(account, password, ip, userAgent, ticks);
            //                //if (token == computedToken)
            //                //{
            //                    result = user;
            //                //}
            //            }

            //        }
            //    }
            //}
            //catch (Exception ex)
            //{
            //    SuperLog.Instance.Error(ex);
            //}

            return result;
        }



        public static bool IsTokenValid(string token, string ip, string userAgent)
        {
            var user = TokenValid(token, ip, userAgent);
            return user != null;
        }
    }
}
